/**
 * 麻点图
 */
import sgisLayerBase from '../../sfgis.layer.base';
import sgisRegionBase from "../../sfgis.region.base.js";
import styleModify from '../macrolayers/echarts.stylemodify.js';
import * as microAPI from "@/pages/micro/api/micro.js";
import searchresultData from "@/pages/micro/views/micro/query/searchresult.data.js";
import mapPopup from './../common/map.popup';
export default {
  layerNum: 0, // 麻点图多能叠加10个，过多时提示移除，防止太卡
  pockingLayer: '',
  colorNum:0,//颜色获取
  colorPng: [
    'pa',
    'pc',
    'pd',
    'pe',
    'pn',
    // 'pm'
  ], // 麻点图配图
  openPopupFunc:null,

  // 重置数据个数
  resetlayerNum() {
    this.layerNum = 0;
  },
  // 初始化图层信息
  initLayer(map, data) {
    const pockingLayerInfo = {};
    pockingLayerInfo.layerId = "pockingLayer_" + data.id + new Date().getTime();
    pockingLayerInfo.layer = "";
    return pockingLayerInfo;
  },
  // 绘制图层
  renderLayer(map, data, item,showMorePanel) {
    let that = this;
    if(showMorePanel){
      that.openPopupFunc = showMorePanel;
    }
    this.colorNum = item.sort;
    let len = data.data.length;
    let param = this.getparam(len);
    map.addSource(item.layerId + "_source", {
      "type": "geojson",
      "cluster": data.data.length > 20000,
      "clusterMaxZoom": param.clusterMaxZoom,
      "clusterRadius": param.clusterRadius,
      "data": { "type": "FeatureCollection", "features": this.formatData(data, item.layerId,map) }
    });

    // if(data.data.length > 10000){
    //   map.addSource(item.layerId + "_source", {
    //     "type": "geojson",
    //     "cluster": data.data.length > 20000,
    //     "clusterMaxZoom": param.clusterMaxZoom,
    //     "clusterRadius": param.clusterRadius,
    //     "data": { "type": "FeatureCollection", "features": this.formatData(data, item.layerId,map,10000) }
    //   });
    // }

    const icon_color = config.pockcolors[this.colorNum]?config.pockcolors[this.colorNum][0]:config.pockcolors[this.colorNum%config.pockcolors.length][0];
    this.initAnimatedIcon(map,icon_color,param.iconSize,this.colorNum);
    map.addLayer({//背景圆
      id: item.layerId+"-clusters",
      type: "circle",
      source: item.layerId + "_source",
      filter: ["has", "point_count"],
      paint: {
          // "circle-color": "rgba("+icon_color+",0.8)",
          "circle-color": [
            "step",
            ["get", "point_count"],
            "rgba("+icon_color+",0.6)",
            100,
            "rgba("+icon_color+",0.75)",
            750,
            "rgba("+icon_color+",0.9)",
          ],
          "circle-radius": [
              "step",
              ["get", "point_count"],
              15,
              100,
              22,
              750,
              30
          ],
           // 这个是外边框的颜色 circle-stroke-color这个对应了上面circle-color
          //  "circle-stroke-color": [
          //     "step",
          //     ["get", "point_count"],
          //     "rgba("+icon_color+",0.3)",
          //     100,
          //     "rgba("+icon_color+",0.3)",
          //     750,
          //     "rgba("+icon_color+",0.3)",
          //   ],
          //   // 这个是外边框晕染的范围
          //   "circle-stroke-width": [
          //     "step",
          //     ["get", "point_count"],
          //     5, //蓝色晕染长度，当点数小于100时为5px晕染
          //     100, //对应上面circle-color 数字，意思为100以内
          //     6, //点计数在100到750之间时为黄色，6px晕染
          //     750, //对应上面circle-color 数字，意思为750以内
          //     7 //点计数大于或等于750时为7px像素的粉红色晕染
          //   ]
      }
    });
    let textColor = config.pockcolors[this.colorNum]?config.pockcolors[this.colorNum][1]:config.pockcolors[this.colorNum%config.pockcolors.length][1];
    map.addLayer({//文字
      id: item.layerId+"-cluster-count",
      type: "symbol",
      source: item.layerId + "_source",
      filter: ["has", "point_count"],
      layout: {
          "text-letter-spacing": -0.5,
          "text-field": "{point_count_abbreviated}",
          "text-font": ["Open Sans Regular","Arial Unicode MS Regular"],
          "symbol-placement": "point",
          "text-size": 13,
          "text-justify":"center",
          "text-anchor":"center",
          "text-padding":0,
          // "text-offset":[0,0]
      },
      paint:{
        "text-color": textColor
      }
    });

    let iconName = 'pulsing-dot'+this.colorNum;

    const icon_image = this.colorPng[this.colorNum]?this.colorPng[this.colorNum]:this.colorPng[this.colorNum%this.colorPng.length];
    map.addLayer({//数据量小使用图标
      "id": item.layerId,
      "type": "symbol",
      "source": item.layerId + "_source",
      "filter": ["!", ["has", "point_count"]],
      "layout": {
        "icon-image": [
          'case',
          ['all',['==',['get','icon_image'],'one']],
          icon_image,
          ['all',['==',['get','icon_image'],'one_out']],
          iconName,
          icon_image
        ],
        "icon-size":param.iconSize,
        "icon-allow-overlap": true,
        // "icon-offset": [0, 0] // 设置偏移量
      }
    });

    // 添加数据点击事件
    map.on('click', item.layerId, e => {

      const popup = new mapboxgl.Popup({ maxWidth: 'none' });
      const el = document.createElement('div');
      el.className = 'pocking-cus-click';
      el.innerHTML = "<div id='"+e.features[0].properties.id+"'>" + e.features[0].properties.name + "</div>";
      popup.setLngLat(e.lngLat.toArray())
        .setDOMContent(el) // sets a popup on this marker
        .addTo(map);

      this.pockClickEvent();
    });
    // 鼠标移入时显示popup
    map.on('mouseenter', item.layerId, e => {
      const popup = new mapboxgl.Popup({ maxWidth: 'none' });
      const el = document.createElement('div');
      el.className = 'pocking-cus';
      el.innerHTML = "<div>" + e.features[0].properties.name + "</div>";
      popup.setLngLat(e.lngLat.toArray())
        .setDOMContent(el) // sets a popup on this marker
        .addTo(map);
    });
    // 鼠标移出时候移除popup
    // eslint-disable-next-line no-unused-vars
    map.on('mouseout', item.layerId, e => {
      $(".pocking-cus").parent().parent().remove();
    });

    const pockingMarkers = map.getLayer(item.layerId);

    const pockingLayer = pockingMarkers;
    const pockingCircleLayer = map.getLayer(item.layerId+"-clusters");
    const pockingClusterCountLayer = map.getLayer(item.layerId+"-cluster-count");
    this.pockingLayer = pockingLayer;
    pockingLayer.setVisible = this.setVisible; // 添加设置可见性函数
    pockingLayer.setOpacity = this.setOpacity; // 添加设置图层透明度函数
    pockingLayer.setZIndexOffsetHasGroup = this.setZIndexOffsetHasGroup; // 设置图层顺序函数
    pockingLayer.autoCalgraph = this.autoCalgraph; // 添加计算图例函数
    pockingLayer.name = data.name;
    pockingLayer.layerNum = item.sort;

    pockingCircleLayer.setVisible = this.setVisible; // 添加设置可见性函数
    pockingCircleLayer.setOpacity = this.setOpacity; // 添加设置图层透明度函数

    pockingClusterCountLayer.setVisible = this.setVisible; // 添加设置可见性函数
    pockingClusterCountLayer.setOpacity = this.setOpacity; // 添加设置图层透明度函数

    const pockLayerInfo = {};
    pockLayerInfo.layerId = item.layerId;

    pockLayerInfo.name = data.name;
    pockLayerInfo.type = 'pockingLayer';
    pockLayerInfo.show = data.showThumbnails !== false;
    pockLayerInfo.html = this.calgraph(pockingLayer, pockLayerInfo.layerId);
    map.overlayerInfos[item.layerId] = pockLayerInfo;
    map.overlayers[item.layerId] = pockingLayer;
    map.overlayers[item.layerId+"-clusters"] = pockingCircleLayer;
    map.overlayers[item.layerId+"-cluster-count"] = pockingClusterCountLayer;

    const zIndex = styleModify.curZindex - item.sort;// 结果展示多个结果导致图层顺利不固定问题
    styleModify.layerOrderHasGroup[item.type][pockLayerInfo.layerId] = zIndex;
    styleModify.setLayerOrder(zIndex, pockingLayer, item.layerId);
    sgisLayerBase.setOverLayers(pockLayerInfo);


  },
  //渲染动画
  initAnimatedIcon(map,icon_color,size,colorNum){
    var size = size*70||40;
    var pulsingDot = {
      width: size,
      height: size,
      data: new Uint8Array(size * size * 4),

      // get rendering context for the map canvas when layer is added to the map
      onAdd: function() {
        var canvas = document.createElement('canvas');
        canvas.width = this.width;
        canvas.height = this.height;
        this.context = canvas.getContext('2d');
      },

      // called once before every frame where the icon will be used
      render: function() {
        var duration = 1000;
        var t = (performance.now() % duration) / duration;

        var radius = (size / 2) * 0.3;
        // var outerRadius = (size / 2) * 0.7 * t + radius;
        var outerRadius = (size / 2) * 1 * t;
        var context = this.context;

        // draw outer circle
        context.clearRect(0, 0, this.width, this.height);
        context.beginPath();
        context.arc(
          this.width / 2,
          this.height / 2,
          outerRadius,
          0,
          Math.PI * 2
        );
        context.fillStyle = "rgba("+icon_color+','+(1 - t) + ")";
        context.fill();

        // draw inner circle
        context.beginPath();
        context.arc(
        this.width / 2,
        this.height / 2,
        radius,
        0,
        Math.PI * 2
        );
        // context.fillStyle = 'rgba(255, 100, 100, 1)';
        context.fillStyle = 'rgba('+icon_color+','+'1)';
        context.strokeStyle = 'white';
        context.lineWidth = 2 + 4 * (1 - t);
        context.fill();
        context.stroke();

        // update this image's data with data from the canvas
        this.data = context.getImageData(
          0,
          0,
          this.width,
          this.height
        ).data;

        // continuously repaint the map, resulting in the smooth animation of the dot
        map.triggerRepaint();

        // return `true` to let the map know that the image was updated
        return true;
      }
    };
    let iconName = 'pulsing-dot'+colorNum;
    if(map.hasImage(iconName)){
      // map.removeImage(iconName);
      map.updateImage(iconName, pulsingDot, { pixelRatio: 2 });
    }else{
      map.addImage(iconName, pulsingDot, { pixelRatio: 2 });
    }
  },
  //麻点名称点击事件
  pockClickEvent(){
    let that = this;
    $(".pocking-cus-click").bind("click", function() {
      mapPopup.clearPopup();
      let eleId =  ($(this).find("div")).attr("id");
      that.getDWInfo(eleId);

    })
  },
  //查询单位信息
  getDWInfo(eleId){
    let that = this;
    let selectedObjTable = sessionStorage.getItem("selectedObjTable");
    let microId = JSON.parse(selectedObjTable).id;
    let req = {
      id : eleId,
      microId : microId
    }
    microAPI
      .getBuildDWInfo(req)
      .then(response => {
        if (response.message == "success") {
          let data = response.data;
          let DWInfo = {
            head:data.head,
            content:{
              records:[]
            }
          }

          DWInfo.content.records.push(data.content);
          let popupData = searchresultData.initMarkerData(DWInfo);
          // 清除popup
          $(".pocking-cus").parent().parent().remove();
          $(".pocking-cus-click").parent().parent().remove();
          mapPopup.openPopup(popupData[0],that.openPopupFunc);
        }else {
          that.$message({
            message: response.message,
            type: "error"
          });
          return;
        }
      })
      .catch(error => {
        console.log(error);
      });
  },
  //动态添加数据到麻点专题图
  insertDataToPock(map,layerId,data){
    let that = this;
    // map.getSource(layerId + "_source").setData({
    //   "type": "FeatureCollection",
    //   "features": that.formatData(data, layerId)
    // }) /* getSource():获取id为layerId的source，使用setData()填充数据  */
    var url = 'https://wanderdrone.appspot.com/';
    map.getSource(layerId + "_source").setData(url) /* getSource():获取id为layerId的source，使用setData()填充数据  */
  },
  //根据数据量设置麻点大小
  getparam(len){
    let param = {
      clusterMaxZoom:7,
      clusterRadius:30,
      iconSize:1
    }
    if(len <10000||len == 10000){
      param.clusterMaxZoom=7;
      param.clusterRadius=40;
      param.iconSize=1;
    }else if(len >10000&&len <50000||len == 50000){
      param.clusterMaxZoom=9;
      param.clusterRadius=45;
      param.iconSize=0.6;
    }else if(len >50000&&len <100000||len == 100000){
      param.clusterMaxZoom=10;
      param.clusterRadius=45;
      param.iconSize=0.4;
    }else if(len >100000&&len <150000||len == 150000){
      param.clusterMaxZoom=11;
      param.clusterRadius=50;
      param.iconSize=0.4;
    }else if(len >150000&&len <200000||len == 200000){
      param.clusterMaxZoom=12;
      param.clusterRadius=50;
      param.iconSize=0.2;
    }else if(len >200000&&len <300000||len == 300000){
      param.clusterMaxZoom=13;
      param.clusterRadius=50;
      param.iconSize=0.1;
    }else{
      param.clusterMaxZoom=15;
      param.clusterRadius=50;
      param.iconSize=0.05;
    }
    return param;

  },
  /**
   * 格式化数据为geojson
   * @param data
   * @param layerId
   * @returns {Array}
   */
  formatData(data, layerId,map,length) {
    const result = [];
    if (data.data !== null && data.data !== undefined) {
      for (let i = 0; i < data.data.length; i++) {
        const temp = data.data[i];
        // 无坐标的数据处理
        if(null === temp.lon || "null" === temp.lon || null === temp.lat || "null" === temp.lat){
          continue;
        }
        let status = "one";
        // 小于十万的时候才去做数据及错误判断，如果是区县及以上没意义
        if(sgisRegionBase.regionInfos.getCurrentRegionLevel() > 4){
          if(data.data.length < 100000){
            let qhdmStatus = temp.jzwdm&&temp.qhdm&&temp.jzwdm.indexOf(temp.qhdm)==-1?false:true
            // 减少点在面内的判断次数（点在面内的判断很慢）如果建筑物编码和区划代码不一致的时候才去判断点在不在区域内
            if(!qhdmStatus){
              var pt = turf.point([temp.lon,temp.lat]);
              var bounds = sgisRegionBase.regionInfos.getCurrentRegionBounds();
              var poly = {};//判断点是否在选中区划面里
              let isInOrOut = false;
              if(bounds.features.length > 1){
                // 获取当前区划对应的面,如果多个面的时候不能只取0
                let regionlevel = sgisRegionBase.regionUtils.getRegionLevel(bounds.features[0].properties.QH_CODE);
                let regionSub = sgisRegionBase.regionUtils.getSubCode(temp.qhdm,regionlevel);
                for(var j = 0 ; j < bounds.features.length ; j++){
                  let geoRegion = sgisRegionBase.regionUtils.getPrefixCode(bounds.features[j].properties.QH_CODE);
                  if(regionSub === geoRegion){
                    poly = turf.multiPolygon(bounds.features[j].geometry.coordinates)
                    isInOrOut = turf.booleanPointInPolygon(pt, poly);
                    break;
                  }
                }
              }else {
                poly = turf.multiPolygon(bounds.features[0].geometry.coordinates);//判断点是否在选中区划面里
                isInOrOut = turf.booleanPointInPolygon(pt, poly);
              }
              if(isInOrOut){
                status = "one";
              }else {
                status = "one_out";
              }
            }else {
              status = "one";
            }
          }
        }

        const feature = {
          "type": "feature",
          "geometry": {
            "type": "Point",
            "coordinates": [
              parseFloat(temp.lon),
              parseFloat(temp.lat)
            ]
          },
          "properties": {
            "value": null,
            "id": temp.id,
            "name": temp.name,
            "lId": layerId,
            "icon_image":status
          }
        };
        result.push(feature);
      }
    }
    return result;
  },
  /**
   *
   * @param {Object} laryer
   * @param {String} colorParam
   */
  // setCustomColor(laryer, colorParam) {
  //   console.log(laryer, colorParam)
  //   const options = laryer[0].chart.getOption();
  //   console.log(options)
  // },
  /* *图层样式可见性设置函数 */
  setVisible(visible, map, layer) {
    if (visible === "visible") { // 显示图层
      map.setLayoutProperty(layer.id, 'visibility', 'visible');
    } else if (visible === "hidden") {  // 隐藏图层
      map.setLayoutProperty(layer.id, 'visibility', 'none');
      // 清除popup
      $(".pocking-cus").parent().parent().remove();
      $(".pocking-cus-click").parent().parent().remove();
    } else {
      return;
    }
  },
  /* *设置图层透明度 */
  // eslint-disable-next-line no-unused-vars
  setOpacity(opacity) {
    // this[0]._container.style.opacity = opacity;
  },
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index, layerId) {
    styleModify.setZIndexOffset(index, layerId);
  },
  setZIndexOffsetHasGroup(index, layerId, chartType) {
    styleModify.setZIndexOffsetHasGroup(index, layerId, chartType);
  },
  /* *图例样式计算 */
  // eslint-disable-next-line no-unused-vars
  calgraph(pockingLayer, layerId) {
    // eslint-disable-next-line no-unused-vars,eqeqeq
    let iconImage = this.colorPng[this.colorNum]?this.colorPng[this.colorNum]:this.colorPng[this.colorNum%this.colorPng.length];
    let clustercolor = "static/images/pages/" + iconImage + ".png";
    let html = `<div style="padding:10px 0;" class="${layerId}">`;
    html += `<div class='chart_item'  style='text-align:center;border-radius:60px;display:inline-block;padding:5px;'>
        <img  src="${clustercolor}"> </img>
        <p   style='line-height: 1;'>${pockingLayer.name || '麻点图'}</p>
    </div>`;
    html += '</div>';
    return html;
  },
  autoCalgraph(layerId, color) {
    const itemColor = color;
    const emphsisColor = 'red';
    const html = `
     <div class="${layerId}" style='text-align:center;padding:10px;line-height :50px'>
        <div style='display:inline-block;width:10px;height:10px;background:${itemColor};border-radius:10px' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
        <div style='display:inline-block;width:10px;height:10px;background:${itemColor};border-radius:10px;' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
        <div style='width:10px;height:10px;background:${itemColor};border-radius:10px' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
     </div>
    `;
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
  }
};
